import React, { useMemo, useState } from 'react'
import { Header, AlertTip } from 'src/components'
import { vipCart } from 'src/api/getData'
import { useSelector } from 'react-redux'
import classNames from 'classnames'

const UseCart = () => {

    const { userInfo } = useSelector(state => state)
    const [alertText, setAlertText] = useState();
    const [cartNumber, setCartNumber] = useState()
    const [showAlert, setShowAlert] = useState(false)
    const [passWord, setPassWord] = useState()

    const onClose = () => {
        setShowAlert(false)
    }

    const couldPay = useMemo(() => {
        return (/^\d{10}$/.test(cartNumber)) && (/^\d{6}$/.test(passWord));
    }, [cartNumber, passWord])

    const confrimPay = async () => {
        if (couldPay) {
            let res = await vipCart(userInfo.id, cartNumber, passWord);
            if (res.message) {
                setPassWord(true)
                setAlertText(res.message)
            } else if (res.name) {
                setPassWord(true)
                setAlertText(res.name)
            }
        }
    }

    return <div className="page_vipcard_usecart">
        <Header title="兑换会员" goBack></Header>
        <p className="buy_for">成功兑换后将关联到当前帐号： <span>{userInfo.username}</span></p>
        <form className="form_style">
            <input type="text" name="cartNumber" maxlength="10" value={cartNumber}
                onInput={(e) => setCartNumber(e.target.value)}
                placeholder="请输入10位卡号" />
            <input type="text" name="passWord" maxlength="6"
                value={passWord}
                onInput={(e) => setPassWord(e.target.value)}
                placeholder="请输入6位卡密" />
        </form>
        <p className={classNames('determine', { could_pay: couldPay })} onClick={confrimPay}>兑换</p>
        <footer className="Binding">
            <h3>——温馨提示——</h3>
            <p>新兑换的会员服务，权益以「会员说明」为准。</p>
            <p>月卡：<b>30次</b>减免配送费。</p>
            <p>季卡：<b>90次</b>减免配送费。</p>
            <p>年卡：<b>360</b>次减免配送费。</p>
            <p>＊仅限蜂鸟专送订单，每日最多减免3单，每单最高减免4元（一个月按31天计算）</p>
        </footer>
        {showAlert && <AlertTip onClose={onClose} alertText={alertText}></AlertTip>}
    </div>
}

export default UseCart